package com.yyfax.ph.base;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import com.umeng.analytics.MobclickAgent;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IEvent;
import com.yyfax.infrastructure.mvp.ViewActivity;
import com.yyfax.ph.R;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.utils.ToastUtils;
import com.yyfax.ph.main.MainActivity;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * 自带顶部视图（标题栏）
 * Dialog显示/隐藏
 * Toast显示/隐藏
 */
public abstract class BaseActivity extends ViewActivity implements View.OnClickListener {
	private static final String TAG = "BaseActivity";

	private FrameLayout mContentView;
	protected RelativeLayout mTopBar;
	protected ImageButton mBtnBack;
	protected TextView mBtnRightTx;
	protected TextView mTitleLeft;
	protected TextView mTitleCenter;
	private ImageButton mBtnSearch;
	private View mTopBarDividerView;

	private DialogBase mTipsDialog;

	public boolean mIgnoreGesture = false;

	@Override
	protected void onDestroy() {
		if (null != mTipsDialog && mTipsDialog.isShowing()) {
			mTipsDialog.dismiss();
		}
		mTipsDialog = null;
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(getClass().getSimpleName());
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(getClass().getSimpleName());
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_base_view);
		initBaseView();
		pretreatmentAfterSetBaseView();
		setContentView(getContentViewRes());
		ButterKnife.bind(this);
		initContentView();
		restoreInstanceState(savedInstanceState);
	}

	public abstract void pretreatmentAfterSetBaseView();

	private void initBaseView() {
		mContentView = (FrameLayout) findViewById(R.id.content_layout_container);
		mTopBar = (RelativeLayout) findViewById(R.id.layout_top_bar);
		mTopBar.setBackgroundColor(getTopBarBackgroundColor());
		mBtnBack = (ImageButton) findViewById(R.id.btn_back);
		mBtnRightTx = (TextView) findViewById(R.id.btn_right_text);
		mTitleCenter = (TextView) findViewById(R.id.title_center);
		mTitleLeft = (TextView) findViewById(R.id.title_left);
		mBtnSearch = (ImageButton) findViewById(R.id.btn_right_image);
		mTopBarDividerView = findViewById(R.id.top_bar_divider_view);
		mBtnBack.setOnClickListener(this);
		mBtnRightTx.setOnClickListener(this);
		mBtnSearch.setOnClickListener(this);
	}

	public abstract int getTopBarBackgroundColor();

	@Override
	public void setContentView(int layoutId) {
		View view = LayoutInflater.from(this).inflate(layoutId, null);
		setContentView(view);
	}

	@Override
	public void setContentView(View view) {
		if (mContentView.getChildCount() > 1) {
			mContentView.removeViewAt(1);
		}
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1);
		mContentView.addView(view, lp);
	}

	public abstract int getContentViewRes();

	public abstract void initContentView();

	/**
	 * 有些控件需要根据Activity的Bundle进行初始化 比如加载高德地图的MapView 供子类重写
	 */
	public void restoreInstanceState(Bundle savedInstanceState) {
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		FragmentManager fm = getSupportFragmentManager();
		int index = requestCode >> 16;
		if (index != 0) {
			index--;
			if (fm.getFragments() == null || index < 0 || index >= fm.getFragments().size()) {
				CLog.w(TAG, "Activity result fragment index out of range: 0x" + Integer.toHexString(requestCode));
				return;
			}
			Fragment frag = fm.getFragments().get(index);
			if (frag == null) {
				CLog.w(TAG, "Activity result no fragment exists for index: 0x" + Integer.toHexString(requestCode));
			} else {
				handleResult(frag, requestCode, resultCode, data);
			}
		}
	}

	/**
	 * 递归调用，对所有子Fragment生效
	 */
	private void handleResult(Fragment frag, int requestCode, int resultCode, Intent data) {
		frag.onActivityResult(requestCode & 0xffff, resultCode, data);
		List<Fragment> frags = frag.getChildFragmentManager().getFragments();
		if (frags != null) {
			for (Fragment f : frags) {
				if (f != null)
					handleResult(f, requestCode, resultCode, data);
			}
		}
	}

	public int getColors(int id) {
		return ContextCompat.getColor(this, id);
	}

	public void onBackBtnPressed() {
	}

	public void onRightBtnPressed() {
	}

	public void onRightImgPressed() {
	}

	public void setTopBarVisible(boolean flag) {
		mTopBar.setVisibility(flag ? View.VISIBLE : View.GONE);
		mTopBarDividerView.setVisibility(flag ? View.VISIBLE : View.GONE);
	}

	public void setTopBarDividerViewVisible(boolean flag){
		mTopBarDividerView.setVisibility(flag ? View.VISIBLE : View.GONE);
	}

	public void setTitle(String title) {
		mTitleCenter.setText(title);
	}

	public void setTitle(SpannableString title) {
		mTitleCenter.setText(title);
	}

	public void setTitle(int id) {
		mTitleCenter.setText(id);
	}

	public void setTitleVisible(boolean flag) {
		mTitleCenter.setVisibility(flag ? View.VISIBLE : View.GONE);
	}

	public void setTitleLeftVisible(boolean flag) {
		mTitleLeft.setVisibility(flag ? View.VISIBLE : View.GONE);
	}

	public void setBtnBackVisible(boolean flag) {
		mBtnBack.setVisibility(flag ? View.VISIBLE : View.GONE);
	}

	public void setBtnBackEnable(boolean flag) {
		mBtnBack.setEnabled(flag);
	}

	public void setBtnRightTx(int id) {
		mBtnRightTx.setText(id);
	}

	public void setBtnRightColor() {
	}

	public String getBtnRightTx() {
		return mBtnRightTx.getText().toString();
	}

	public void setBtnRightVisible(boolean flag) {
		mBtnRightTx.setVisibility(flag ? View.VISIBLE : View.GONE);
	}

	public ImageButton getRightSearchBtn() {
		return mBtnSearch;
	}

	protected void setRightImageBtnVisible(boolean show){
		mBtnSearch.setVisibility(show ? View.VISIBLE : View.GONE);

	}

	protected void setRightImageBtnSrc(int resId, int bgId){
		mBtnSearch.setBackgroundResource(bgId);
		mBtnSearch.setImageResource(resId);
	}

	protected void setTopBarBackgroundColor(int color){
		mTopBar.setBackgroundColor(color);
	}

	protected void setTitleCenterColor(int color){
		mTitleCenter.setTextColor(color);
	}

	protected void setBtnBackBackground(@DrawableRes int drawable){
		mBtnBack.setImageResource(drawable);
	}


	public void showCallDialog(final String phone){
		showTipsDialog(phone, R.string.cancel, R.string
				.call_the_phone, new DialogBase.BottomTwoClickListener() {
			@Override
			public void onCancelClick(DialogBase dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirmClick(DialogBase dialog) {
				confirmCall();
				dialog.dismiss();
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
				startActivity(intent);
			}
		});
	}

	public void confirmCall() {
	}

	public void showTipsDialog(String tips) {
		if (mTipsDialog != null && mTipsDialog.isShowing()) {
			mTipsDialog.dismiss();
		}
		mTipsDialog = new DialogBase(this, null, tips, getString(R.string.confirm), new DialogBase.BottomOneClickListener() {
			@Override
			public void bottomOneClick(DialogBase dialog) {
				dialog.dismiss();
			}
		});
		mTipsDialog.show();
	}

	public void showTipsDialog(String tips, boolean cancelAble) {
		if (mTipsDialog != null && mTipsDialog.isShowing()) {
			mTipsDialog.dismiss();
		}
		mTipsDialog = new DialogBase(this, null, tips, getString(R.string.confirm), new DialogBase.BottomOneClickListener() {
			@Override
			public void bottomOneClick(DialogBase dialog) {
				dialog.dismiss();
			}
		}, cancelAble);
		mTipsDialog.show();
	}

	public void showTipsDialog(String tips, DialogBase.BottomOneClickListener listener) {
		if (mTipsDialog != null && mTipsDialog.isShowing()) {
			mTipsDialog.dismiss();
		}
		mTipsDialog = new DialogBase(this, null, tips, getString(R.string.confirm), listener);
		mTipsDialog.show();
	}

	public void showTipsDialog(String title, String tips, boolean cancelAble) {
		if (mTipsDialog != null && mTipsDialog.isShowing()) {
			mTipsDialog.dismiss();
		}
		mTipsDialog = new DialogBase(this, title, tips, getString(R.string.confirm), new DialogBase.BottomOneClickListener() {
			@Override
			public void bottomOneClick(DialogBase dialog) {
				dialog.dismiss();
			}
		}, cancelAble);
		mTipsDialog.show();
	}

	public void showTipsDialog(String tips, DialogBase.BottomOneClickListener listener, boolean cancel) {
		if (mTipsDialog != null && mTipsDialog.isShowing()) {
			mTipsDialog.dismiss();
		}
		mTipsDialog = new DialogBase(this, null, tips, getString(R.string.confirm), listener, cancel);
		mTipsDialog.show();
	}

	public void showTipsDialog(String tips, int tipsBottomOne, int tipsBottomTwo, DialogBase.BottomTwoClickListener listener) {
		if (mTipsDialog != null && mTipsDialog.isShowing()) {
			mTipsDialog.dismiss();
		}
		mTipsDialog = new DialogBase(this, null, tips, getString(tipsBottomOne), getString(tipsBottomTwo), listener);
		mTipsDialog.show();
	}

	public void showTipsDialog(String tips, int tipsBottomOne, int tipsBottomTwo, DialogBase.BottomTwoClickListener listener, boolean cancel) {
		if (mTipsDialog != null && mTipsDialog.isShowing()) {
			mTipsDialog.dismiss();
		}
		mTipsDialog = new DialogBase(this, null, tips, getString(tipsBottomOne), getString(tipsBottomTwo), listener, cancel);
		mTipsDialog.show();
	}

	public void showTipsDialog(int tips) {
		if (mTipsDialog != null && mTipsDialog.isShowing()) {
			mTipsDialog.dismiss();
		}
		mTipsDialog = new DialogBase(this, null, getString(tips),
				getString(R.string.confirm),
				new DialogBase.BottomOneClickListener() {
					@Override
					public void bottomOneClick(DialogBase dialog) {
						dialog.dismiss();
					}
				}
		);
		mTipsDialog.show();
	}

	public void showToast(int id) {
		ToastUtils.showToast(BaseActivity.this, getString(id));
	}

	protected void showToast(String text) {
		ToastUtils.showToast(BaseActivity.this, text);
	}

	/**
	 * 最左边和最右边按钮的点击事件
	 * todo 如果子类也需要实现View.OnClickListener接口，会不会有冲突
	 */
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.btn_back:
				onBackBtnPressed();
				break;
			case R.id.btn_right_text:
				onRightBtnPressed();
				break;
			case R.id.btn_right_image:
				onRightImgPressed();
				break;
		}
	}

	/**
	 * 会话超时处理
	 *
	 * @param event 会话超时event
	 */
	@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
	public void handleSessionTimeout(IEvent.UnLoginEvent event) {
		EventAgent.removeStickyEvent(event);
		// 这里再判断一下，如果当前标记是登录状态才往下传，否则说明已经是未登录状态了，不需要再跳转，防止多次跳转。
		if (YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
			// 会话超时，需要清除本地会话缓存
			YJPH.getInstance().onLogoutSuccess();
			logoutToHomePage();
		}
	}

	/**
	 * 会话超时，或退出登录界面时，则跳转到首页，
	 * 解决修改密码，修改手机号后退栈回到的界面依然是已登录状态的问题。
	 */
	protected void logoutToHomePage() {
		if (!YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
			MainActivity.start(this, true);
		}
	}
}
